package cn.edu.scut.sys.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import cn.edu.scut.sys.dao.UnitDao;
import cn.edu.scut.sys.service.UnitService;
import cn.edu.scut.sys.utils.DataRequest;
import cn.edu.scut.sys.utils.DataResponse;
import cn.edu.scut.sys.vo.Unit;

@Component("unitService")
public class UnitServiceImpl implements UnitService{

private UnitDao unitDao;
	
	@Resource(name="unitDao")
	public void setUserDao(UnitDao unitDao) {
		this.unitDao = unitDao;
	}

	@Override
	public DataResponse<Unit> list(DataRequest request, String unitIdStr) {
		DataResponse<Unit> response = new DataResponse<Unit>();  
        int count;//总记录数  
        int limit = request.getRows() <= 0 ? 20 : request.getRows();//每页显示数量  
        int totalPages;//总页数  
        int page = request.getPage() <= 0 ? 1 : request.getPage();//当前显示页码  
        List<Unit> list;  
          
        count = unitDao.count().intValue();  
        totalPages = count / limit;  
        if (count % limit != 0) {  
            totalPages++;  
        }  
        int currPage = Math.min(totalPages, page);  
          
        int start = currPage * limit - limit;  
        start = start < 0 ? 0 : start;
        Long unitId = 1L;
        try{
        	unitId = Long.parseLong(unitIdStr);
        } catch(Exception ex) {
        	unitId = 1L;
        }
        list = unitDao.list(start, limit, request.getSord(), request.getSidx(), unitId);  
        response.setRecords(count);  
        response.setTotal(totalPages);  
        response.setPage(currPage);  
        response.setRows(list);  
          
        return response;  
	}

	@Override
	public boolean add(Unit unit) {
		unitDao.insert(unit);
		return true;
	}

	@Override
	public Unit get(Long id) {
		return unitDao.get(id);
	}

	@Override
	public boolean update(Unit unit) {
		unitDao.update(unit);
		return true;
	}

	@Override
	public List<Unit> listByUnitId(Long unitId) {
		return unitDao.listByUnitId(unitId);
	}
}
